#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);
  this->setWindowTitle("TCP服务端");
  m_tcpServer = new TcpServer(this);
}

Widget::~Widget() { delete ui; }

void Widget::on_btnStart_clicked() {
  if (!m_start) {
    QString ip = ui->lineEditIP->text();
    uint port = ui->lineEditPort->text().toUInt();
    bool ret = m_tcpServer->listen(QHostAddress(ip), port);
    if (ret) {
      ui->messageShoxEdit->appendPlainText("服务器启动成功！");
      ui->btnStart->setText("停止");
      m_start = true;
    } else {
      ui->messageShoxEdit->appendPlainText("服务器启动失败！");
    }
  } else {
    // 关闭TCP的监听
    m_tcpServer->close();
    ui->messageShoxEdit->appendPlainText("服务器已停止!");
    ui->btnStart->setText("启动");
    m_start = false;
  }
}

void Widget::showMessage(const QString &info, bool conn) {
  ui->messageShoxEdit->appendPlainText(info);
}

void Widget::on_btnSend_clicked() {
  // 获取要发送的内容
  QString msg = ui->messageEdit->text();
  QByteArray data = msg.toUtf8(); // 转换为utf8字节数组
  m_tcpServer->sendData(data);
}
